package cn.cdtu.tibetplan.controller;

import java.util.ArrayList;
import java.util.List;

import cn.cdtu.tibetplan.pojo.*;
import cn.cdtu.tibetplan.service.*;
import cn.cdtu.tibetplan.util.Tools;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private RolemenuService rolemenuService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    /**
     * 登录
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public Result login(User user, HttpSession session,Model model) {
        if (user != null && user.getUsername() != "" && user.getPassword() != "") {
            User u = userService.login(user);
            if (u != null) {
                session.setAttribute("username", u.getUsername());
//                model.addAttribute("userId",u.getId());
                session.setAttribute("userId",u.getId());
                return new Result(true, "登录成功");
            }
        }
        return new Result(false, "用户名或密码错误");
    }



    /**
     * 注册
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/register")
    public String register(User user,HttpSession session) {
        if (user != null && user.getUsername() != "" && user.getPassword() != "") {
            // 密码加密
            user.setPassword(Tools.md5(user.getPassword()));
            user.setCreatetime((Tools.getTime()));
            user.setLevel(5);
            user.setOperator("admin");
            return userService.register(user);
        }
        return "error";
    }

    /**
     * 退出登录
     *
     * @param session
     */
    @ResponseBody
    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        if(session.getAttribute("username") != null && session.getAttribute("userId") != null){
            session.removeAttribute("username");
            session.removeAttribute("userId");
        }
//        session.setAttribute("username", "");
//        session.setAttribute("userId","");
    }

    /**
     * 返回全部列表
     *
     * @return
     */
    @RequestMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    @RequestMapping("/list")
    public String list() {
        return "redirect:search?currentPage=1&pageSize=10";
    }

    @RequestMapping("/search")
    public String search(User user, int currentPage, int pageSize, Model model) {
        List<School> schools = schoolService.findAll();
        model.addAttribute("schools", schools);
        PageResult result = userService.findPage(user, currentPage, pageSize);
        PageEnd pageend = new PageEnd(result.getTotal(), result.getRows(), currentPage, pageSize);
        model.addAttribute("pageEnd", pageend);
        return "/User/index";
    }

    /**
     * 修改密码页面跳转
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/pwd")
    public String pwd(Long id, Model model) {
//        User user = userService.findOne(id.longValue());
//        User user = userService.findOne((long) 1);
//        model.addAttribute("user", user);
        return "/User/pwd";
    }

    /**
     * 修改密码
     *
     * @param password
     * @param newPwd
     * @return
     */
    @ResponseBody
    @RequestMapping("/changePwd")
    public Result changePwd(Long id,String password, String newPwd) {
        try {
            User user = userService.findOne(id);
            if (user.getPassword().equals(Tools.md5(password))) {
                user.setPassword(Tools.md5(newPwd));
                userService.update(user);
                return new Result(true, "修改成功");
            } else {
                return new Result(false, "原密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    /**
     * 添加用户跳转
     *
     * @param model
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(Model model) {
        List<School> list = schoolService.findAll();
        model.addAttribute("schools", list);
        return "/User/add";
    }

    /**
     * 增加
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/add")
    public Result add(User user) {
        try {
            user.setCreatetime(Tools.getTime());
            user.setPassword(Tools.md5(user.getPassword()));
            user.setOperator("admin");
            String schoolname = schoolService.findOne(user.getSchoolid().longValue()).getSchoolname();
            if (schoolname != "") {
                user.setSchoolname(schoolname);
                userService.add(user);
                return new Result(true, "增加成功");
            }
            return new Result(false, "增加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "增加失败");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(Long[] ids) {
        try {
            userService.delete(ids);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

    /**
     * 修改跳转
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Long id, Model model) {
        List<Role> roles = roleService.findAll();
        model.addAttribute("roles",roles);
        User user = userService.findOne(id.longValue());
        model.addAttribute("edit", user);
        return "/User/edit";
    }

    /**
     * 修改
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/update")
    public Result update(User user) {
        try {
            userService.update(user);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    /**
     * 获取实体
     *
     * @param id
     * @return
     */
    @RequestMapping("/findOne")
    public User findOne(Long id) {
        return userService.findOne(id);
    }

    /**
     * 查看具体信息
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/show")
    public String show(Long id, Model model) {
        User user = userService.findOne(id.longValue());
        model.addAttribute("show", user);
        return "/User/show";
    }

    @RequestMapping("/getMenu")
    @ResponseBody
    public String getMenu(long userId){
        User user = userService.findOne(userId);
        Rolemenu rm=new Rolemenu();
        rm.setRoleid(Integer.valueOf(user.getLevel()));
        //PageResult rolePageResult = rolemenuService.findPage(rm, 1, 0);
        List<Rolemenu> roleRows = rolemenuService.findByRoleId(rm);//角色的菜单列表
        List<Integer> menuids=new ArrayList<>();//角色菜单id集合
        for(Rolemenu rlm:roleRows){
            if(rlm.getMenuid()!=0){
                menuids.add(rlm.getMenuid());
            }
        }
        System.out.println(menuids.size()+"333");
        List<Menus> allMenus = getAllMenus();
        for(Menus m:allMenus){
            if(menuids.contains(m.getId())){
                m.setChecked(false);
            }
            List<Menus> children = m.getChildren();
            if(children!=null&&children.size()>0){
                boolean flag=false;
                for(Menus ms:children){
                    if(menuids.contains(ms.getId())){
                        ms.setChecked(true);
                        flag=true;
                    }
                }
                if(flag){
                    m.setChecked(true);
                }
            }
        }
        List<IndexMenu> indexMenus=new ArrayList<>();
        for(Menus m:allMenus){
            IndexMenu m1=new IndexMenu();
            m1.setId(m.getId());
            m1.setHref(m.getHref());
            m1.setText(m.getTitle());
            if(m.getChildren().size()>0){
                List<IndexMenu> ch=new ArrayList<>();
                boolean flag=false;
                for(Menus mm:m.getChildren()){
                    if(mm.isChecked()){
                        IndexMenu m2=new IndexMenu();
                        m2.setId(mm.getId());
                        m2.setText(mm.getTitle());
                        m2.setHref(mm.getHref());
                        ch.add(m2);
                        flag=true;
                    }
                }
                m1.setItems(ch);
                if(flag){
                    indexMenus.add(m1);
                }
            }
        }
        return JSON.toJSONString(indexMenus);
    }


    //获取所有菜单
    private List<Menus> getAllMenus(){
        final List<Menu> menuRows = findMenuByPId(0);//一级菜单 pId=0
        List<Menus> result=new ArrayList<>();
        for(Menu mr:menuRows){
            List<Menu> childrenMenu = findMenuByPId(mr.getId());
            Menus ms=new Menus();
            ms.setId(mr.getId());
            ms.setHref(mr.getLink());
            ms.setTitle(mr.getName());
            ms.setSpread(true);
            if(childrenMenu.size()>0){
                List<Menus> children=new ArrayList<>();
                for(Menu m2:childrenMenu){
                    Menus mc=new Menus();
                    mc.setId(m2.getId());
                    mc.setTitle(m2.getName());
                    mc.setHref(m2.getLink());
                    mc.setSpread(true);
                    children.add(mc);
                }
                ms.setChildren(children);
            }
            result.add(ms);
        }
        return  result;
    }

    private List<Menu> findMenuByPId(int pId){
        Menu m=new Menu();
        m.setPid(pId);
        return menuService.findByPId(m);
    }
}
